import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox
from PIL import Image, ImageTk
import json
import os
import webbrowser
from functools import partial
import threading
import time

class MathTeacherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("传播数学的魅力")
        self.root.geometry("1200x700")
        self.root.configure(bg="#f0f9ff")
        
        # 加载级联数据
        self.cascade_data = self.load_cascade_data()
        
        # 创建主框架
        self.main_frame = tk.Frame(root, bg="#f0f9ff")
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 创建左右面板
        self.create_panels()
        
        # 设置初始内容
        self.display_eight_steps()
        
        # 图片预览变量
        self.image_path = None
        self.image_preview = None

    def load_cascade_data(self):
        # 这里使用与HTML版本相同的级联数据
        return {
            "primary": {
                "一年级": {
                    "数字王国": [
                        "20以内的数的认识", "20以内的加减法", "简单的应用题",
                        "100以内数的认识", "整十数的加减法", "认识人民币"
                    ],
                    "形状世界": [
                        "立体图形的认识", "平面图形的认识", "上下左右位置",
                        "长度单位认识", "简单图形分类"
                    ]
                },
                "二年级": {
                    "计算乐园": [
                        "100以内的加减法", "表内乘法", "简单除法",
                        "整百数的认识", "时间的认识", "人民币的换算"
                    ],
                    "几何探索": [
                        "角的认识", "平面图形的边和角", "图形的拼组",
                        "厘米和米的认识", "简单的测量"
                    ]
                },
                "三年级": {
                    "数学基础": [
                        "万以内数的认识", "万以内的加减法", "表内除法",
                        "分数的初步认识", "小数的初步认识"
                    ],
                    "图形空间": [
                        "平行与垂直", "周长的概念", "长方形和正方形的周长",
                        "面积的初步认识"
                    ]
                },
                "四年级": {
                    "数字游戏": [
                        "万以上数的认识", "四则运算", "简单的小数加减",
                        "分数的基本性质", "分数的大小比较"
                    ],
                    "测量大师": [
                        "角度的测量", "三角形的认识", "平行四边形",
                        "面积的计算", "数学日记"
                    ]
                },
                "五年级": {
                    "数字王国": [
                        "小数的性质", "小数的四则运算", "分数加减法",
                        "可能性的大小", "百分数的认识"
                    ],
                    "形状世界": [
                        "三角形的面积", "梯形的面积", "扇形的认识",
                        "体积和容积的认识"
                    ]
                },
                "六年级": {
                    "计算乐园": [
                        "分数乘除法", "比的理解", "比例的应用",
                        "百分数的应用", "整数指数幂"
                    ],
                    "几何探索": [
                        "圆的理解", "圆的周长和面积", "圆柱和圆锥",
                        "比例尺的应用", "数据统计"
                    ]
                }
            },
            "junior": {
                "初一": {
                    "数与式": [
                        "有理数的认识", "有理数运算", "整式的加减",
                        "一元一次方程", "数据的收集与整理"
                    ],
                    "图形与几何": [
                        "几何图形初步", "角与平行线", "三角形的基本性质",
                        "轴对称图形", "图形的初步认识"
                    ]
                },
                "初二": {
                    "代数": [
                        "整式的乘除", "因式分解", "分式",
                        "二元一次方程组", "一次函数"
                    ],
                    "几何": [
                        "三角形的证明", "全等三角形", "四边形",
                        "平行四边形", "矩形、菱形、正方形"
                    ]
                },
                "初三": {
                    "数学": [
                        "二次函数", "一元二次方程", "二次根式",
                        "勾股定理", "相似图形", "圆"
                    ],
                    "统计与概率": [
                        "统计的基本步骤", "频数与频率", "概率的意义",
                        "简单事件的概率"
                    ]
                }
            },
            "senior": {
                "高一": {
                    "集合与函数": [
                        "集合的概念", "集合的运算", "函数的概念",
                        "函数的性质", "指数函数", "对数函数"
                    ],
                    "三角函数": [
                        "角的概念与弧度制", "三角函数的定义", "诱导公式",
                        "三角函数的图像", "三角恒等式"
                    ]
                },
                "高二": {
                    "平面向量": [
                        "向量的概念", "向量的运算", "向量的坐标表示",
                        "向量的应用"
                    ],
                    "数列": [
                        "数列的概念", "等差数列", "等比数列",
                        "数列的极限"
                    ],
                    "立体几何": [
                        "空间几何体的特征", "空间点线面的位置关系",
                        "空间向量", "立体图形的度量"
                    ]
                },
                "高三": {
                    "解析几何": [
                        "直线方程", "圆的方程", "圆锥曲线",
                        "曲线的参数方程"
                    ],
                    "概率与统计": [
                        "计数原理", "概率的定义", "条件概率",
                        "正态分布"
                    ],
                    "微积分初步": [
                        "导数的概念", "导数的应用", "积分的概念",
                        "定积分的应用"
                    ]
                }
            },
            "college": {
                "大一": {
                    "高等数学基础": [
                        "函数极限", "连续性", "导数与微分",
                        "积分学基础"
                    ],
                    "线性代数": [
                        "矩阵运算", "线性方程组", "向量空间",
                        "特征值与特征向量"
                    ]
                },
                "大二": {
                    "数学分析": [
                        "多元函数微分", "重积分", "曲线积分",
                        "曲面积分"
                    ],
                    "概率论": [
                        "随机变量", "概率分布", "大数定律",
                        "中心极限定理"
                    ]
                },
                "大三": {
                    "复变函数": [
                        "解析函数", "复积分", "留数理论",
                        "共形映射"
                    ],
                    "微分方程": [
                        "一阶方程", "高阶线性方程", "稳定性理论",
                        "数值解法"
                    ]
                },
                "大四": {
                    "泛函分析": [
                        "度量空间", "赋范空间", "Hilbert空间",
                        "算子理论"
                    ],
                    "数学建模": [
                        "优化模型", "微分方程模型", "概率统计模型",
                        "元胞自动机"
                    ]
                }
            }
        }

    def create_panels(self):
        # 创建左侧面板
        self.left_panel = tk.Frame(self.main_frame, bg="white", padx=15, pady=15, 
                                  highlightbackground="#e2e8f0", highlightthickness=1)
        self.left_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=(0, 10))
        
        # 创建右侧面板
        self.right_panel = tk.Frame(self.main_frame, bg="white", padx=15, pady=15,
                                   highlightbackground="#e2e8f0", highlightthickness=1)
        self.right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 设置左侧面板内容
        self.setup_left_panel()
        
        # 设置右侧面板内容
        self.setup_right_panel()

    def setup_left_panel(self):
        # 标题
        title_label = tk.Label(self.left_panel, text="传播数学的魅力", font=("Arial", 16, "bold"), 
                              bg="white", fg="#334155")
        title_label.pack(pady=(0, 15))
        
        # 使用说明框
        instruction_frame = tk.Frame(self.left_panel, bg="#f8fafc", padx=10, pady=10,
                                    highlightbackground="#e2e8f0", highlightthickness=1)
        instruction_frame.pack(fill=tk.X, pady=(0, 15))
        
        instruction_title = tk.Label(instruction_frame, text="使用说明：", font=("Arial", 10, "bold"),
                                    bg="#f8fafc", fg="#334155")
        instruction_title.pack(anchor=tk.W)
        
        instructions = [
            "1. 选择学段（小学、初中、高中或大学）",
            "2. 选择对应年级、章节、知识点",
            "3. 输入您的数学问题（可选择上传图片）",
            "4. 点击\"提交问题\"按钮获取解答"
        ]
        
        for instruction in instructions:
            instr_label = tk.Label(instruction_frame, text=instruction, font=("Arial", 9),
                                  bg="#f8fafc", fg="#334155", justify=tk.LEFT, anchor=tk.W)
            instr_label.pack(anchor=tk.W, pady=2)
        
        tip_label = tk.Label(instruction_frame, text="提示：选择越精确，解答越准确。问题描述应尽量清晰具体。上传图片可帮助系统更好理解复杂问题。",
                            font=("Arial", 8), bg="#f8fafc", fg="#64748b", wraplength=300, justify=tk.LEFT)
        tip_label.pack(anchor=tk.W, pady=(5, 0))
        
        # 表单
        form_frame = tk.Frame(self.left_panel, bg="white")
        form_frame.pack(fill=tk.X)
        
        # 学段选择
        level1_label = tk.Label(form_frame, text="学段", font=("Arial", 10), bg="white", fg="#334155")
        level1_label.pack(anchor=tk.W, pady=(10, 5))
        
        self.level1_var = tk.StringVar()
        self.level1_combobox = ttk.Combobox(form_frame, textvariable=self.level1_var, state="readonly", width=30)
        self.level1_combobox['values'] = ["请选择学段", "小学", "初中", "高中", "大学"]
        self.level1_combobox.current(0)
        self.level1_combobox.pack(fill=tk.X, pady=(0, 10))
        self.level1_combobox.bind("<<ComboboxSelected>>", self.on_level1_change)
        
        # 年级选择
        level2_label = tk.Label(form_frame, text="年级", font=("Arial", 10), bg="white", fg="#334155")
        level2_label.pack(anchor=tk.W, pady=(10, 5))
        
        self.level2_var = tk.StringVar()
        self.level2_combobox = ttk.Combobox(form_frame, textvariable=self.level2_var, state="disabled", width=30)
        self.level2_combobox['values'] = ["请先选择学段"]
        self.level2_combobox.current(0)
        self.level2_combobox.pack(fill=tk.X, pady=(0, 10))
        self.level2_combobox.bind("<<ComboboxSelected>>", self.on_level2_change)
        
        # 章节选择
        level4_label = tk.Label(form_frame, text="章节", font=("Arial", 10), bg="white", fg="#334155")
        level4_label.pack(anchor=tk.W, pady=(10, 5))
        
        self.level4_var = tk.StringVar()
        self.level4_combobox = ttk.Combobox(form_frame, textvariable=self.level4_var, state="disabled", width=30)
        self.level4_combobox['values'] = ["请先选择年级"]
        self.level4_combobox.current(0)
        self.level4_combobox.pack(fill=tk.X, pady=(0, 10))
        self.level4_combobox.bind("<<ComboboxSelected>>", self.on_level4_change)
        
        # 知识点选择
        level5_label = tk.Label(form_frame, text="知识点", font=("Arial", 10), bg="white", fg="#334155")
        level5_label.pack(anchor=tk.W, pady=(10, 5))
        
        self.level5_var = tk.StringVar()
        self.level5_combobox = ttk.Combobox(form_frame, textvariable=self.level5_var, state="disabled", width=30)
        self.level5_combobox['values'] = ["请先选择章节"]
        self.level5_combobox.current(0)
        self.level5_combobox.pack(fill=tk.X, pady=(0, 10))
        
        # 问题描述
        question_label = tk.Label(form_frame, text="问题描述", font=("Arial", 10), bg="white", fg="#334155")
        question_label.pack(anchor=tk.W, pady=(10, 5))
        
        question_frame = tk.Frame(form_frame, bg="white")
        question_frame.pack(fill=tk.X)
        
        # 上传图片按钮
        upload_button = tk.Button(question_frame, text="📷", font=("Arial", 12), bg="#f3f4f6",
                                 command=self.upload_image, width=3, height=1)
        upload_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 问题文本框
        self.question_text = scrolledtext.ScrolledText(form_frame, height=4, width=30, font=("Arial", 10))
        self.question_text.pack(fill=tk.X, pady=(5, 10))
        
        # 图片预览区域
        self.preview_frame = tk.Frame(form_frame, bg="white")
        self.preview_frame.pack(fill=tk.X, pady=(0, 10))
        self.preview_frame.pack_forget()  # 初始隐藏
        
        # 提交按钮
        self.submit_button = tk.Button(form_frame, text="提交问题", font=("Arial", 10, "bold"),
                                     bg="#3b82f6", fg="white", activebackground="#2563eb",
                                     activeforeground="white", height=2, command=self.submit_question)
        self.submit_button.pack(fill=tk.X, pady=(10, 0))

    def setup_right_panel(self):
        # 创建加载指示器框架
        self.loading_frame = tk.Frame(self.right_panel, bg="white")
        self.loading_frame.pack(fill=tk.BOTH, expand=True)
        self.loading_frame.pack_forget()  # 初始隐藏
        
        loading_label = tk.Label(self.loading_frame, text="正在思考中...", font=("Arial", 12), bg="white", fg="#334155")
        loading_label.pack(pady=20)
        
        # 创建答案容器
        self.answer_frame = tk.Frame(self.right_panel, bg="white")
        self.answer_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建可滚动区域
        self.canvas = tk.Canvas(self.answer_frame, bg="white")
        scrollbar = ttk.Scrollbar(self.answer_frame, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = tk.Frame(self.canvas, bg="white")
        
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )
        
        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=scrollbar.set)
        
        self.canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

    def display_eight_steps(self):
        # 清空当前内容
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 标题
        title_label = tk.Label(self.scrollable_frame, text="八步解题法", font=("Arial", 18, "bold"), 
                              bg="white", fg="#334155")
        title_label.pack(pady=(0, 20))
        
        # 创建网格布局框架
        grid_frame = tk.Frame(self.scrollable_frame, bg="white")
        grid_frame.pack(fill=tk.BOTH, expand=True, padx=10)
        
        steps = [
            {"title": "第一步：读题，也叫审题", "desc": "仔细阅读题目，理解问题要求和条件。", "bg": "#EBF5FF", "fg": "#3B82F6"},
            {"title": "第二步：列出所有的已知条件", "desc": "整理题目中给出的所有信息和条件。", "bg": "#ECFDF5", "fg": "#10B981"},
            {"title": "第三步：评估条件", "desc": "分析已知条件是否足够解题，是否有多余信息。", "bg": "#FFFBEB", "fg": "#F59E0B"},
            {"title": "第四步：思考题目背后的知识点", "desc": "确定解题需要用到的数学概念和公式。", "bg": "#F5F3FF", "fg": "#8B5CF6"},
            {"title": "第五步：思考多种解题思路", "desc": "尝试不同的解题方法，选择最合适的一种。", "bg": "#FEF2F2", "fg": "#EF4444"},
            {"title": "第六步：开始解题", "desc": "按照选定的方法，一步步进行计算和推导。", "bg": "#EEF2FF", "fg": "#6366F1"},
            {"title": "第七步：遇到困难及时换思路", "desc": "如果解题过程遇到障碍，尝试其他方法。", "bg": "#FDF2F8", "fg": "#EC4899"},
            {"title": "第八步：不被多余条件影响解题", "desc": "专注于解题必要的条件，忽略无关信息。", "bg": "#F0FDFA", "fg": "#14B8A6"}
        ]
        
        # 创建步骤卡片
        row, col = 0, 0
        for i, step in enumerate(steps):
            step_frame = tk.Frame(grid_frame, bg=step["bg"], padx=10, pady=10,
                                 highlightbackground=step["fg"], highlightthickness=1)
            step_frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
            
            step_title = tk.Label(step_frame, text=step["title"], font=("Arial", 11, "bold"),
                                 bg=step["bg"], fg=step["fg"])
            step_title.pack(anchor=tk.W, pady=(0, 5))
            
            step_desc = tk.Label(step_frame, text=step["desc"], font=("Arial", 10),
                               bg=step["bg"], fg="#334155", wraplength=200)
            step_desc.pack(anchor=tk.W)
            
            col += 1
            if col > 1:
                col = 0
                row += 1
        
        # 配置网格权重
        for i in range(4):
            grid_frame.grid_rowconfigure(i, weight=1)
        for i in range(2):
            grid_frame.grid_columnconfigure(i, weight=1)
        
        # 底部提示
        tip_label = tk.Label(self.scrollable_frame, text="请在左侧选择学段、年级、章节和知识点，并输入您的问题",
                           font=("Arial", 10), bg="white", fg="#64748b")
        tip_label.pack(pady=20)

    def on_level1_change(self, event):
        level1 = self.level1_combobox.get()
        level1_map = {"小学": "primary", "初中": "junior", "高中": "senior", "大学": "college"}
        
        if level1 in level1_map:
            level1_key = level1_map[level1]
            grades = list(self.cascade_data.get(level1_key, {}).keys())
            
            self.level2_combobox['values'] = ["请选择年级"] + grades
            self.level2_combobox.current(0)
            self.level2_combobox['state'] = 'readonly'
            
            # 重置其他下拉框
            self.level4_combobox['values'] = ["请先选择年级"]
            self.level4_combobox.current(0)
            self.level4_combobox['state'] = 'disabled'
            
            self.level5_combobox['values'] = ["请先选择章节"]
            self.level5_combobox.current(0)
            self.level5_combobox['state'] = 'disabled'
        else:
            self.level2_combobox['state'] = 'disabled'

    def on_level2_change(self, event):
        level1 = self.level1_combobox.get()
        level2 = self.level2_combobox.get()
        level1_map = {"小学": "primary", "初中": "junior", "高中": "senior", "大学": "college"}
        
        if level1 in level1_map and level2 != "请选择年级":
            level1_key = level1_map[level1]
            chapters = list(self.cascade_data.get(level1_key, {}).get(level2, {}).keys())
            
            self.level4_combobox['values'] = ["请选择章节"] + chapters
            self.level4_combobox.current(0)
            self.level4_combobox['state'] = 'readonly'
            
            # 重置知识点下拉框
            self.level5_combobox['values'] = ["请先选择章节"]
            self.level5_combobox.current(0)
            self.level5_combobox['state'] = 'disabled'
        else:
            self.level4_combobox['state'] = 'disabled'

    def on_level4_change(self, event):
        level1 = self.level1_combobox.get()
        level2 = self.level2_combobox.get()
        level4 = self.level4_combobox.get()
        level1_map = {"小学": "primary", "初中": "junior", "高中": "senior", "大学": "college"}
        
        if level1 in level1_map and level2 != "请选择年级" and level4 != "请选择章节":
            level1_key = level1_map[level1]
            knowledge_points = self.cascade_data.get(level1_key, {}).get(level2, {}).get(level4, [])
            
            self.level5_combobox['values'] = ["请选择知识点"] + knowledge_points
            self.level5_combobox.current(0)
            self.level5_combobox['state'] = 'readonly'
        else:
            self.level5_combobox['state'] = 'disabled'

    def upload_image(self):
        file_path = filedialog.askopenfilename(
            title="选择图片",
            filetypes=[("图片文件", "*.png *.jpg *.jpeg *.gif *.bmp")]
        )
        
        if file_path:
            self.image_path = file_path
            self.display_image_preview(file_path)

    def display_image_preview(self, file_path):
        # 清除现有预览
        for widget in self.preview_frame.winfo_children():
            widget.destroy()
        
        # 显示预览框架
        self.preview_frame.pack(fill=tk.X, pady=(5, 10))
        
        # 加载并调整图片大小
        image = Image.open(file_path)
        image.thumbnail((150, 150))  # 调整为缩略图大小
        photo = ImageTk.PhotoImage(image)
        
        # 创建预览容器
        preview_container = tk.Frame(self.preview_frame, bg="white", 
                                    highlightbackground="#e2e8f0", highlightthickness=1)
        preview_container.pack(anchor=tk.W)
        
        # 显示图片
        image_label = tk.Label(preview_container, image=photo, bg="white")
        image_label.image = photo  # 保持引用
        image_label.pack(side=tk.LEFT)
        
        # 添加删除按钮
        remove_button = tk.Button(preview_container, text="×", font=("Arial", 10, "bold"),
                                 bg="#ef4444", fg="white", width=2, height=1,
                                 command=self.remove_image_preview)
        remove_button.pack(side=tk.LEFT, anchor=tk.N)

    def remove_image_preview(self):
        self.image_path = None
        self.preview_frame.pack_forget()

    def submit_question(self):
        level1 = self.level1_combobox.get()
        level2 = self.level2_combobox.get()
        level4 = self.level4_combobox.get()
        level5 = self.level5_combobox.get()
        question = self.question_text.get("1.0", tk.END).strip()
        
        # 检查是否有图片上传
        has_image = self.image_path is not None
        
        # 如果没有上传图片，则需要校验所有选项
        if not has_image:
            if level1 == "请选择学段":
                messagebox.showwarning("提示", "请选择学段")
                return
            
            if level2 == "请选择年级" or level2 == "请先选择学段":
                messagebox.showwarning("提示", "请选择年级")
                return
            
            if level4 == "请选择章节" or level4 == "请先选择年级":
                messagebox.showwarning("提示", "请选择章节")
                return
            
            if level5 == "请选择知识点" or level5 == "请先选择章节":
                messagebox.showwarning("提示", "请选择知识点")
                return
        
        if not question and not has_image:
            messagebox.showwarning("提示", "请输入问题描述或上传图片")
            return
        
        # 显示加载状态
        self.answer_frame.pack_forget()
        self.loading_frame.pack(fill=tk.BOTH, expand=True)
        
        # 根据是否有图片选择不同的处理方法
        if has_image:
            threading.Thread(target=self.process_image_question, args=(level1, level2, level4, level5, question, self.image_path)).start()
        else:
            threading.Thread(target=self.process_text_question, args=(level1, level2, level4, level5, question)).start()

    def process_text_question(self, level1, level2, level4, level5, question):
        # 处理纯文本问题的逻辑
        # 模拟API请求
        time.sleep(2)  # 模拟网络延迟
        
        # 示例回答
        answer = f"您的问题是关于{level1}的{level2}{level4}{level5}的问题：\n\n{question}\n\n这是一个文本问题的回答示例。"
        
        # 更新UI（在主线程中）
        self.root.after(0, lambda: self.update_answer(answer))

    def process_image_question(self, level1, level2, level4, level5, question, image_path):
        # 处理包含图片的问题的逻辑
        # 模拟API请求
        time.sleep(3)  # 模拟网络延迟
        
        # 获取图片文件名
        image_filename = os.path.basename(image_path)
        
        # 示例回答
        answer = f"您上传了图片：{image_filename}\n\n"
        if question:
            answer += f"您的问题描述：{question}\n\n"
        
        if level1 != "请选择学段":
            answer += f"学段：{level1}\n"
        if level2 != "请选择年级" and level2 != "请先选择学段":
            answer += f"年级：{level2}\n"
        if level4 != "请选择章节" and level4 != "请先选择年级":
            answer += f"章节：{level4}\n"
        if level5 != "请选择知识点" and level5 != "请先选择章节":
            answer += f"知识点：{level5}\n\n"
        
        answer += "这是一个图片问题的回答示例。系统已识别您上传的图片内容，并生成相应的解答。"
        
        # 更新UI（在主线程中）
        self.root.after(0, lambda: self.update_answer(answer))
    
    def update_answer(self, answer_text):
        # 隐藏加载状态
        self.loading_frame.pack_forget()
        self.answer_frame.pack(fill=tk.BOTH, expand=True)
        
        # 清空当前内容
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 创建答案标题
        title_label = tk.Label(self.scrollable_frame, text="解答", font=("Arial", 16, "bold"), 
                              bg="white", fg="#334155")
        title_label.pack(pady=(0, 15))
        
        # 创建答案文本区域
        answer_text_widget = scrolledtext.ScrolledText(self.scrollable_frame, height=20, width=60, 
                                                     font=("Arial", 10), wrap=tk.WORD)
        answer_text_widget.pack(fill=tk.BOTH, expand=True, padx=10)
        answer_text_widget.insert(tk.END, answer_text)
        answer_text_widget.configure(state="disabled")  # 设置为只读

    def display_answer(self, answer_html):
        # 隐藏加载状态
        self.loading_frame.pack_forget()
        self.answer_frame.pack(fill=tk.BOTH, expand=True)
        
        # 清空当前内容
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 解析HTML并显示内容
        self.parse_and_display_html(answer_html)

    def parse_and_display_html(self, html):
        # 简单的HTML解析和显示
        # 这里只是一个简化版，实际应用中可能需要更复杂的HTML解析
        
        lines = html.strip().split('\n')
        for line in lines:
            line = line.strip()
            
            if line.startswith('<h2>') and line.endswith('</h2>'):
                text = line[4:-5]
                label = tk.Label(self.scrollable_frame, text=text, font=("Arial", 16, "bold"), 
                               bg="white", fg="#334155")
                label.pack(anchor=tk.W, pady=(15, 5))
                
            elif line.startswith('<h3>') and line.endswith('</h3>'):
                text = line[4:-5]
                label = tk.Label(self.scrollable_frame, text=text, font=("Arial", 14, "bold"), 
                               bg="white", fg="#334155")
                label.pack(anchor=tk.W, pady=(10, 5))
                
            elif line.startswith('<p>') and line.endswith('</p>'):
                text = line[3:-4]
                label = tk.Label(self.scrollable_frame, text=text, font=("Arial", 10), 
                               bg="white", fg="#334155", wraplength=600, justify=tk.LEFT)
                label.pack(anchor=tk.W, pady=5)
                
            elif line.startswith('<ol>'):
                # 创建列表框架
                self.list_frame = tk.Frame(self.scrollable_frame, bg="white")
                self.list_frame.pack(fill=tk.X, padx=20, pady=5)
                self.list_counter = 1
                
            elif line.startswith('<li>') and line.endswith('</li>'):
                text = line[4:-5]
                # 替换<strong>标签
                text = text.replace('<strong>', '').replace('</strong>', '')
                
                list_item = tk.Label(self.list_frame, text=f"{self.list_counter}. {text}", 
                                   font=("Arial", 10), bg="white", fg="#334155", 
                                   wraplength=580, justify=tk.LEFT)
                list_item.pack(anchor=tk.W, pady=2)
                self.list_counter += 1

if __name__ == "__main__":
    root = tk.Tk()
    app = MathTeacherApp(root)
    root.mainloop()